---
- name: install packages
  apt:
    name: "{{ item }}"
    state: present
    # update_cache: yes
  loop:
    - git
    - apt-transport-https
    - nginx
    - gpg
    - cron

- name: check out master branch
  git:
    repo: 'https://github.com/monicahq/monica.git'
    dest: /srv/monicahq
    version: v3.6.0

- name: Add the user
  user:
    name: monicahq
    shell: /usr/bin/nologin
    home: /srv/monicahq

- name: Install sury key
  apt_key:
    url: 'https://packages.sury.org/php/apt.gpg'
    state: present

- name: Add sury repositories
  apt_repository:
    repo: "deb https://packages.sury.org/php/ buster main"
    state: present
    # update_cache: yes
    filename: 'sury'

- name: install php dependencies
  apt:
    name: "{{ item }}"
    state: present
    update_cache: yes
  loop:
    - php7.4
    - php7.4-cli
    - php7.4-intl
    - php7.4-iconv
    - php7.4-fpm
    - php7.4-curl
    - php7.4-gd
    - php7.4-mysql
    - php7.4-mysqli
    - php7.4-opcache
    - php7.4-json
    - php7.4-mbstring
    - php7.4-soap
    - php7.4-xml
    - php7.4-zip
    - php7.4-gmp
    - php7.4-bcmath
    - php-memcached
    - php-xdebug
    - php-redis

- name: reload service php-fcgi
  become: true
  systemd:
    name: php7.4-fpm
    state: reloaded

- name: install composer
  include_role:
    name: geerlingguy.composer

- name: install composer dependencies
  # become_user: monicahq
  environment: 
    COMPOSER_ALLOW_SUPERUSER: 1
  composer:
    command: install
    working_dir: /srv/monicahq

- name: prepare configuration
  template:
    src: env.j2
    dest: /srv/monicahq/.env

- name: Run an initial key generation
  command: "/usr/bin/php /srv/monicahq/artisan key:generate"
  args:
    chdir: /srv/monicahq/
  tags: molecule-notest

- name: Run an initial migration
  command: "/usr/bin/php /srv/monicahq/artisan setup:production --force"
  args:
    chdir: /srv/monicahq/
  tags: molecule-notest

- name: Place a scheduler cron job
  cron:
    user: monicahq
    name: "scheduler"
    job: "/usr/bin/php /srv/monicahq/artisan schedule:run"

- name: Recursively change ownership of a directory
  file:
    path: /srv/monicahq
    state: directory
    recurse: yes
    owner: monicahq
    group: www-data

- name: Put right permissions to storage
  file:
    path: /srv/monicahq/storage
    state: directory
    recurse: yes
    mode: g+w
- name: Create nginx vhost config
  template:
    src: monicahq.conf.j2
    dest: /etc/nginx/sites-enabled/monica.conf
- name: Remove default nginx configuration
  file:
    path: /etc/nginx/sites-enabled/default
    state: absent
- name: reload service nginx
  become: true
  systemd:
    name: nginx
    state: reloaded
